package com.lzx.iteam.net;

import android.content.Context;
import android.os.Message;
import android.util.Log;
import com.lzx.iteam.bean.EventListData;
import com.lzx.iteam.bean.ScheduleData;
import com.lzx.iteam.bean.ScheduleListData;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.provider.ScheduleDB;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.StringUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * **********************************
 * User: zhangshuai
 * Date: 2016年 03月 16日
 * Time: 下午6:14
 *
 * @QQ : 1234567890
 * **********************************
 */
public class GetCalendarMsg extends CcMsgStructure {

    private static final String TAG = "GetCalendarMsg";
    private Message mmCallback;
    private Context mContext;
    private String mYear, mMonth, mDay;
    private String mDate;
    private  String bossUid;
    private ScheduleDB mScheduleDb;
    private CloudDBOperation mCloudDBOperation;

    public GetCalendarMsg(Message callback, Context mContext, String year, String month, String day,String boss) {
        this.mmCallback = callback;
        this.mContext = mContext;
        this.mYear = year;
        this.mMonth = month;
        this.mDay = day;
        this.bossUid = boss;
        mScheduleDb = new ScheduleDB(mContext);
        mCloudDBOperation = new CloudDBOperation(mContext);
        mDate = mYear + "_" + mMonth + "_" + mDay;
    }


    @Override
    public void onReceive(JSONObject data) {

        List<ScheduleListData> listData = new ArrayList<ScheduleListData>();
        List<Object> calendarList = new ArrayList<Object>();
        try {
            mCloudDBOperation.deleteCalendarByDate(bossUid,mYear,mMonth);
            mScheduleDb.deleteScheduleByDate(mDate,bossUid);
            if (!data.isNull(AsynHttpClient.KEY_CC_DATA)) {
                JSONObject jsonObject = data.getJSONObject(AsynHttpClient.KEY_CC_DATA);
                JSONObject mdata = jsonObject.getJSONObject(AsynHttpClient.KEY_CALENDAR);
                Iterator it = mdata.keys();
                List<String> keyListstr = new ArrayList<String>();
                while (it.hasNext()) {
                    keyListstr.add(it.next().toString());
                }

                for (String key : keyListstr) {
                    ScheduleListData scheduleListData = new ScheduleListData();
                    JSONObject schedule = mdata.getJSONObject(key);
                    if (schedule.has("items")){
                        JSONArray items = schedule.getJSONArray("items");
                        if (items.length() > 0) {
                            scheduleListData.setState("1");
                            scheduleListData.setStatus(schedule.getString(AsynHttpClient.KEY_CALENDAR_STATUS));
                            scheduleListData.setYear(mYear);
                            scheduleListData.setMonth(mMonth);
                            scheduleListData.setDay(key + "");
                            scheduleListData.setUserId(bossUid);
                            listData.add(scheduleListData);
                            mCloudDBOperation.insertCalendarListData(scheduleListData);
                        }
                        if (key.equals(mDay)) {
                            for (int i = 0; i < items.length(); i++) {
                                JSONObject calendar = items.getJSONObject(i);
                                String type = calendar.getString("type");
                                if ("1".equals(type)) {
                                    ScheduleData scheduleData = new ScheduleData();
                                    scheduleData.setType("1");
                                    if (calendar.has("hidden") && "1".equals(calendar.getString("hidden")) && !calendar.has("event_title")){
                                        scheduleData.setStartTime(calendar.getString("start_datetime"));
                                        if (calendar.has("end_datetime")){
                                            scheduleData.setEndTime(calendar.getString("end_datetime"));
                                        }
                                        scheduleData.setHidden("1");
                                        calendarList.add(scheduleData);
                                        scheduleData.setBossUid(bossUid);
                                        mScheduleDb.addSchedule("1",mDate,scheduleData);
                                    }else{
                                        if (calendar.has("hidden")){
                                            scheduleData.setHidden(calendar.getString("hidden"));
                                        }else{
                                            scheduleData.setHidden("0");
                                        }
                                        scheduleData.setId(calendar.getString("ID"));
                                        scheduleData.setStartTime(calendar.getString("start_datetime"));
                                        scheduleData.setTitle(calendar.getString("event_title"));
                                        scheduleData.setPublishedUName(calendar.getString("delegater_username"));
                                        scheduleData.setAlertTime(calendar.getString("alert_datetime"));
                                        if (calendar.has("done")){
                                            scheduleData.setDone(calendar.getString("done"));
                                        }else{
                                            scheduleData.setDone("0");
                                        }
                                        scheduleData.setRemark(calendar.getString("remark"));
                                        scheduleData.setNotice(calendar.getString("update"));
                                        scheduleData.setUpdateTime(calendar.getString("update_time"));
                                        scheduleData.setCreateTime(calendar.getString("create_time"));
                                        scheduleData.setPublishedUId(calendar.getString("delegate_user"));
                                        scheduleData.setEndTime(calendar.getString("end_datetime"));
                                        scheduleData.setAddress(calendar.getString("address"));
                                        scheduleData.setHasRead(calendar.getString("has_read"));
                                        scheduleData.setBossUid(calendar.getString("user_id"));
                                        calendarList.add(scheduleData);
                                        mScheduleDb.addSchedule("1",mDate,scheduleData);
                                        if (!"0".equals(scheduleData.getAlertTime()) && scheduleData.getBossUid().equals(bossUid)) {
                                            mCloudDBOperation.insertAlarmWarnData(scheduleData);
                                        }
                                    }

                                } else {
                                    EventListData eventListData = new EventListData();
                                    eventListData.setEventId(calendar.getString("ID"));
                                    eventListData.setUpdateTime(calendar.getString("update_time"));
                                    eventListData.setContent1(calendar.getString("event_content"));
                                    eventListData.setUserId(calendar.getString("user_id"));
                                    eventListData.setEventType("9");
                                    eventListData.setMemberCount(calendar.getString("member_count"));
                                    eventListData.setEventAvatar(calendar.getString("user_img"));
                                    eventListData.setEventTitle(calendar.getString("event_title"));
                                    eventListData.setActivitySite(calendar.getString("event_address"));
                                    eventListData.setActivityTime(calendar.getString("event_time"));
                                    eventListData.setUserType(calendar.getString("user_type"));
                                    if (calendar.has("has_read_count")) {
                                        eventListData.setHasReadCount(calendar.getString("has_read_count"));
                                    }
                                    if (calendar.has("has_read")) {
                                        eventListData.setHasRead(calendar.getString("has_read"));
                                    }
                                    eventListData.setCreateTime(calendar.getString("create_time"));
                                    eventListData.setIsQrcode(calendar.getString("is_qrcode"));
                                    eventListData.setEndTime(calendar.getString("end_datetime"));
                                    eventListData.setUserName(calendar.getString("user_name"));
                                    if (calendar.has("qrcode")) {
                                        eventListData.setQrcode(calendar.getString("qrcode"));
                                    }
                                    calendarList.add(eventListData);
                                    eventListData.setMyUserId(bossUid);
                                    mScheduleDb.addSchedule("9",mDate,eventListData);
                                }

                            }
                            Log.d("key + day", " 数据 ==== " + calendarList.size());
                        }
                    }
                }

            }
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("schedule", listData);
            map.put("calendar", calendarList);

            if (mmCallback != null) {
                mmCallback.arg1 = 0;
                mmCallback.obj = map;
                mmCallback.sendToTarget();
            }

        } catch (Exception e) {
            Log.e(TAG, "error:   " + e.toString());
            e.printStackTrace();
        }
    }


    @Override
    public void onError(int error, Object ret) {
        Log.d(TAG, "onError : " + error + " ret: " + ret);
        String errorMsg = null;
        if (ret != null) {
            JSONObject jData = null;
            try {
                jData = new JSONObject(ret.toString());
                errorMsg = jData.getString("msg");
            } catch (JSONException e) {
                errorMsg = "服务端数据解析失败!";
                e.printStackTrace();
            }

        }
        if (mmCallback != null) {
            mmCallback.arg1 = error;
            if (!StringUtil.isEmpty(errorMsg)) {
                mmCallback.obj = errorMsg;
            } else {
                mmCallback.obj = Constants.NETWORK_WRROR;
            }
            mmCallback.sendToTarget();
        }
    }
}
